<template>
  <view class="h-[100vh] flex flex-col overflow-hidden bg-[#f5f5f5]">
    <!-- 固定头部区域 -->
    <view class="fixed-top left-0 right-0 z-50">
      <S1Header title="快速还款" :on-back="onBack">
        <template #right>
          <!-- 移除催收文案 -->
        </template>
      </S1Header>

      <view class="flex items-center bg-white px-20rpx py-12rpx">
        <view class="relative h-70rpx flex flex-1 items-center rounded-full bg-[#f5f5f5] px-20rpx">
          <image src="https://ceshiweb.picaime.com/static/images/search.png" class="mr-10rpx h-36rpx w-36rpx" />
          <input
            v-model="keywords" class="flex-1 text-28rpx" placeholder="搜索买家名称或手机号" confirm-type="search"
            @confirm="onSearch"
          >
          <view
            v-if="keywords" class="absolute right-20rpx h-40rpx w-40rpx flex items-center justify-center"
            @click="clearKeyword"
          >
            <image class="h-36rpx w-36rpx" src="https://ceshiweb.picaime.com/static/images/close.png" />
          </view>
        </view>
        <view class="ml-16rpx h-40rpx w-40rpx flex items-center justify-center" @click="toggleFilter">
          <image class="h-36rpx w-36rpx" src="https://ceshiweb.picaime.com/static/images/filter.png" />
        </view>
      </view>

      <view v-if="showFilter" class="border-b-[1px] border-t-[1px] border-[#eee] bg-white px-20rpx py-16rpx">
        <view class="mb-16rpx flex justify-between">
          <text class="text-28rpx text-[#333]">
            欠款时间
          </text>
          <view class="flex">
            <text
              class="mr-20rpx rounded-6rpx px-20rpx py-8rpx text-28rpx"
              :class="selectedFilter === 'shortest' ? 'bg-[#007aff] text-white' : 'text-[#666] bg-[#f5f5f5]'"
              @click="setFilter('shortest')"
            >
              时间最短
            </text>
            <text
              class="rounded-6rpx px-20rpx py-8rpx text-28rpx"
              :class="selectedFilter === 'longest' ? 'bg-[#007aff] text-white' : 'text-[#666] bg-[#f5f5f5]'"
              @click="setFilter('longest')"
            >
              时间最长
            </text>
          </view>
        </view>
        <view class="flex justify-between">
          <text class="text-28rpx text-[#333]">
            按金额排序
          </text>
          <view class="flex">
            <text
              class="mr-20rpx rounded-6rpx px-20rpx py-8rpx text-28rpx"
              :class="selectedFilter === 'asc' ? 'bg-[#007aff] text-white' : 'text-[#666] bg-[#f5f5f5]'"
              @click="setFilter('asc')"
            >
              从低到高
            </text>
            <text
              class="rounded-6rpx px-20rpx py-8rpx text-28rpx"
              :class="selectedFilter === 'desc' ? 'bg-[#007aff] text-white' : 'text-[#666] bg-[#f5f5f5]'"
              @click="setFilter('desc')"
            >
              从高到低
            </text>
          </view>
        </view>
      </view>

      <view
        class="flex items-center justify-between border-b-[1px] border-t-[1px] border-[#eee] bg-white px-20rpx py-16rpx"
      >
        <text class="text-28rpx">
          总赊欠：<text class="text-[#FF6B01]">
            {{ formatNumber(totalOwe) }}
          </text>，共<text class="text-[#FF6B01]">
            {{
              totalBuyers
            }}
          </text>人赊欠
        </text>
        <!-- 添加催收文案 -->
        <view class="flex items-center" @click="onCollectionDoc">
          <image src="https://ceshiweb.picaime.com/static/images/pyq.png" class="mr-4rpx h-32rpx w-32rpx" />
          <text class="text-28rpx text-[#007aff]">
            催收文案
          </text>
        </view>
      </view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view
      class="h-[80%] w-full pb-100rpx pt-320rpx" scroll-y refresher-enabled :refresher-triggered="refreshing"
      @scrolltolower="onLoadMore" @refresherrefresh="onPullDown"
    >
      <view
        v-for="(buyer, index) in buyers" :key="index"
        class="mx-20rpx mt-20rpx flex flex-col border-b-[1px] border-[#e5e5e5] bg-white px-20rpx py-24rpx"
      >
        <text class="mb-8rpx block text-[40rpx] text-[#000000] font-400 tracking-[0px]">
          {{ buyer.name }}
        </text>
        <view class="flex items-center">
          <text class="text-28rpx text-[#666]">
            已赊欠：
          </text>
          <text class="flex-1 text-32rpx text-[#FF6B01]">
            {{ formatNumber(buyer.sheqian_total) }}元
          </text>
          <button
            class="h-66rpx w-138rpx flex items-center justify-center rounded-6rpx border-none bg-[#43CF7C] text-28rpx text-white"
            @click="onRepay(buyer)"
          >
            还款
          </button>
        </view>
      </view>
      <view class="h-32rpx w-full">
        <view v-if="loading && buyers.length > 0" class="flex items-center justify-center py-20rpx">
          <text class="text-28rpx text-[#999]">
            加载中...
          </text>
        </view>
        <view v-if="noMore && buyers.length > 0" class="flex items-center justify-center py-20rpx">
          <text class="text-28rpx text-[#999]">
            没有更多数据了
          </text>
        </view>
      </view>
    </scroll-view>

    <view
      v-if="showActionMenu" class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
      @click="showActionMenu = false"
    >
      <view class="w-600rpx overflow-hidden rounded-12rpx bg-white" @click.stop>
        <view class="border-b-[1px] border-[#f0f0f0] py-24rpx text-center">
          <text class="text-36rpx font-bold">
            操作
          </text>
        </view>
        <view class="border-b-[1px] border-[#f0f0f0] px-24rpx py-32rpx">
          <view class="mb-16rpx flex items-center">
            <text class="text-32rpx text-[#333] font-500">
              {{ currentBuyer?.name }}
            </text>
          </view>
          <view class="mb-16rpx flex items-center">
            <text class="text-28rpx text-[#666]">
              已赊欠：
            </text>
            <text class="text-32rpx text-[#FF6B01] font-bold">
              {{ formatNumber(currentBuyer?.sheqian_total || 0)
              }}元
            </text>
          </view>
          <view class="flex items-center">
            <text class="text-28rpx text-[#666]">
              还款金额：
            </text>
            <input
              v-model="repayAmount" type="digit"
              class="ml-16rpx flex-1 border-b-[1px] border-[#eee] px-12rpx py-8rpx text-32rpx" placeholder="请输入还款金额"
            >
          </view>
        </view>
        <view class="flex border-b-[1px] border-[#f0f0f0]">
          <button class="h-88rpx flex-1 bg-white text-32rpx text-[#666]" @click="showActionMenu = false">
            取消
          </button>
          <button class="h-88rpx flex-1 bg-[#43CF7C] text-32rpx text-white" @click="submitRepay">
            确认还款
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { MemberListsReq } from '@/api/member/types';
import { ref, watch } from 'vue';
import { getMemberLists } from '@/api/member';
import * as S1Header from '@/components/S1Header.vue';

interface Buyer {
  name: string;
  oweAmount?: number;
  phone?: string;
  lastOweTime?: string;
  id?: number;
  sheqian_total: number;
  maijia_id?: number;
  no_pay_total?: number;
  sheqian_last_date?: string;
}

// 基础数据
const keywords = ref('');
const totalOwe = ref(0);
const totalBuyers = ref(0);
const loading = ref(false);
const refreshing = ref(false);
const noMore = ref(false);
const page = ref(1);
const pageSize = ref(10);

// 防抖定时器
let searchDebounce: ReturnType<typeof setTimeout> | null = null;

// 监听搜索关键词变化
watch(keywords, (newVal) => {
  // 清除之前的定时器
  if (searchDebounce) clearTimeout(searchDebounce);

  // 设置新的定时器，延迟300ms执行搜索
  searchDebounce = setTimeout(() => {
    loadData(true);
  }, 300);
});

// 筛选相关
const showFilter = ref(false);
const selectedFilter = ref('');

// 还款相关
const showActionMenu = ref(false);
const currentBuyer = ref<Buyer | null>(null);
const repayAmount = ref('');

// 买家列表
const buyers = ref<Buyer[]>([]);

// 页面初始化
onShow(() => {
  loadData(true);
});

// 页面操作
function onBack() {
  uni.navigateBack();
}

function onCollectionDoc() {
  console.log('催收文案');
  uni.showToast({
    title: '催收文案功能开发中',
    icon: 'none',
  });
}

function onSearch() {
  console.log('搜索:', keywords.value);
  loadData(true);
}

function clearKeyword() {
  keywords.value = '';
  loadData(true);
}

function toggleFilter() {
  showFilter.value = !showFilter.value;
}

function setFilter(type: string) {
  // 如果点击的是当前选中的选项，则取消选中
  if (selectedFilter.value === type) {
    selectedFilter.value = '';
  }
  else {
    selectedFilter.value = type;
  }
  loadData(true);
}

function formatNumber(num: number) {
  return num.toLocaleString();
}

// 列表相关
function onPullDown() {
  console.log('下拉刷新');
  refreshing.value = true;
  loadData(true).finally(() => {
    refreshing.value = false;
  });
}

function onLoadMore() {
  console.log('加载更多');
  if (loading.value || noMore.value) return;
  loadData();
}

async function loadData(reset = false) {
  if (reset) {
    page.value = 1;
    noMore.value = false;
  }

  loading.value = true;
  try {
    // 构建请求参数
    const params: MemberListsReq = {
      page: page.value,
      limit: pageSize.value,
    };

    // 添加关键词搜索
    if (keywords.value) {
      params.keywords = keywords.value;
    }

    // 添加筛选参数
    switch (selectedFilter.value) {
      case 'shortest':
        params.options_order_status_value = '3';
        break;
      case 'longest':
        params.options_order_status_value = '4';
        break;
      case 'asc':
        params.options_order_status_value = '1';
        break;
      case 'desc':
        params.options_order_status_value = '2';
        break;
    }

    // 调用接口获取数据
    const res = await getMemberLists(params);

    if (res.code === 200 && res.data) {
      // 更新总数据
      totalOwe.value = res.data.total_price || 0;
      totalBuyers.value = res.data.total_num || 0;

      // 处理列表数据
      const memberData = res.data.data;
      const newBuyers: Buyer[] = (memberData.data || []).map(item => ({
        id: item.id,
        maijia_id: item.maijia_id,
        name: item.maijia || '未知买家',
        oweAmount: item.no_pay_total || 0,
        sheqian_total: item.sheqian_total || 0,
        lastOweTime: item.sheqian_last_date,
      }));

      // 更新列表数据
      if (reset) {
        buyers.value = newBuyers;
      }
      else {
        buyers.value = [...buyers.value, ...newBuyers];
      }

      // 判断是否还有更多数据
      if (memberData.current_page >= memberData.last_page) {
        noMore.value = true;
      }
      else {
        page.value++;
      }
    }
    else {
      uni.showToast({
        title: res.msg || '获取数据失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('加载数据失败', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none',
    });
  }
  finally {
    loading.value = false;
  }
}

// 还款相关
function onRepay(buyer: Buyer) {
  // 跳转到赊欠订单页面
  uni.navigateTo({
    url: `/pages/common/creditOrderList/creditOrderList?maijia_id=${buyer.maijia_id}`,
  });
}

function submitRepay() {
  const amount = Number.parseFloat(repayAmount.value);
  if (!amount || isNaN(amount)) {
    uni.showToast({
      title: '请输入有效的还款金额',
      icon: 'none',
    });
    return;
  }

  if (amount > (currentBuyer.value?.sheqian_total || 0)) {
    uni.showToast({
      title: '还款金额不能大于欠款金额',
      icon: 'none',
    });
    return;
  }

  console.log('提交还款', currentBuyer.value, amount);

  // 模拟API调用
  uni.showLoading({
    title: '处理中',
  });

  setTimeout(() => {
    uni.hideLoading();
    showActionMenu.value = false;

    uni.showToast({
      title: '还款成功',
      icon: 'success',
    });

    // 更新数据
    if (currentBuyer.value) {
      const buyer = buyers.value.find(b => b.id === currentBuyer.value?.id);
      if (buyer) {
        buyer.sheqian_total -= amount;
        totalOwe.value -= amount;
      }
    }
  }, 1500);
}
</script>

<style scoped>
.fixed-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
}

.header-placeholder {
  height: 320rpx;
  /* 增加默认高度 */
}

.header-placeholder.with-filter {
  height: 440rpx;
  /* 增加过滤器显示时的高度 */
}
</style>
